package com.fs.web.base.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 *  MD5加密
 * @author wuge
 * @date 2018/8/21
 */
@Slf4j
public class EncodeUtil {

	/**
	 * 	加密
	 * @param str 加密字符串
	 * @param charSet 加密字符格式
	 * @return 加密后字符
	 */
	public static String strToMd5(String str, String charSet) {
		String md5Str = null;
		MessageDigest md = null;
		if (str != null && str.length() != 0) {
			try {
				md = MessageDigest.getInstance("MD5");
				md.update(str.getBytes(charSet));
			} catch (Exception e) {
				e.printStackTrace();
				log.error("加密出错");
			}
			byte[] b = md.digest();
			int i;
			StringBuilder buf = new StringBuilder("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0) {
					i += 256;
				}
				if (i < 16) {
					buf.append("0");
				}
				buf.append(Integer.toHexString(i));
			}
			md5Str = buf.toString();
		}
		return md5Str;
	}

	/**
	 * 按照字典序逆序拼接参数
	 *
	 * @param params
	 * @return
	 */
	public static String getSign(String... params) {
		List<String> srcList = new ArrayList<String>();
		for (String param : params) {
			srcList.add(param);
		}
		// 按照字典序逆序拼接参数
		Arrays.sort(params);
		Collections.sort(srcList, String.CASE_INSENSITIVE_ORDER);
		Collections.reverse(srcList);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < srcList.size(); i++) {
			sb.append(srcList.get(i));
		}
		return sb.toString();
	}

	/***
	 * MD5加密调用
	 */
	public static String getSignAndMD5(String... params) {
		String sign = getSign(params);
			return strToMd5(sign, "utf-8");
	}

	public static void main(String[] args) {

		System.out.println(getSignAndMD5("s"));
    }
}
